package org.apache.commons.dbuils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Objects;

import javax.sql.DataSource;

/**
 * @author 付大石
 */
public class QueryRunner extends AbstractQueryRunner {

    public QueryRunner(DataSource dataSource) {
        super(dataSource);
    }
    
    
    // -------------------------------
    // for SELECT
    // --------------------------------
    
    // -------------------------------
    // for INSERT DELETE and UPDATE
    // --------------------------------
    public int update(String sql) throws SQLException {
        Connection conn = super.prepareConnection();
        return update(conn, false, sql, new Object[0]);
    }

    public int update(Connection conn, String sql) throws SQLException {
        return update(conn, false, sql, new Object[0]);
    }

    public int update(String sql, Object... params) throws SQLException {
        Connection conn = super.prepareConnection();
        return update(conn, false, sql, params);
    }

    public int update(Connection conn, String sql, Object... params) throws SQLException {
        return update(conn, false, sql, params);
    }

    private int update(Connection conn, boolean closeConn, String sql, Object... params) throws SQLException {

        // 参数校验 //
        Objects.requireNonNull(conn, "参数conn不能为null");
        Objects.requireNonNull(params, "参数params不能为null");
        if (sql == null) {
            if (closeConn) {
                DbUtils.close(conn);
                throw new NullPointerException("参数sql不能为null");
            }
        }

        // 执行sql语句 //
        int rows = 0;
        PreparedStatement pStatement = null;
        try {
            pStatement = super.prepareStatement(conn, sql);
            super.fillStatement(pStatement, params); // 为预处理语句填充参数
            rows = pStatement.executeUpdate();
        } catch (SQLException e) {
            throw new SQLException("执行失败", e);
        } finally {
            try {
                DbUtils.close(pStatement);
            } finally {
                if (closeConn) {
                    DbUtils.close(conn);
                }
            }
        }
        return rows;
    }
    
    // -------------------------------
    // for INSERT
    // --------------------------------
}
